package org.gjy.m8.thread;

import org.junit.Test;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-07-31 21:21:38
 */
public class CyclicBarrierTest {

    @Test
    public void test1() throws InterruptedException {
        CyclicBarrier barrier = new CyclicBarrier(3, () -> System.out.println("end"));

        ExecutorService pool = Executors.newFixedThreadPool(3);

        AtomicInteger integer = new AtomicInteger();
        for (int i = 0; i < 8; i++) {
            integer.set(i);
            pool.execute(() -> {
                try {
                    System.out.println("start " + integer.get());
                    barrier.await();
                    System.out.println("end " + integer.get());
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            });
            TimeUnit.SECONDS.sleep(1);
        }

        pool.shutdown();
    }
}
